package jnpf.htgl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.ActionResult;
import jnpf.htgl.entity.*;
import jnpf.htgl.enums.ExpenseTypeEnum;
import jnpf.htgl.mapper.*;
import jnpf.htgl.model.zcglhtglinfo.*;
import jnpf.htgl.service.ZcglHtglInfoService;
import jnpf.htgl.service.ZcglHtglPabService;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 合同管理
 * 版本： V3.2.0
 * 版权： 智果云科技（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-01-12
 */
@Service
public class ZcglHtglInfoServiceImpl extends ServiceImpl<ZcglHtglInfoMapper, ZcglHtglInfoEntity> implements ZcglHtglInfoService {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;

    @Autowired
    private ZcglHtglPabService zcglHtglPabService;
    @Autowired
    private ZcglHtglPabMapper zcglHtglPabMapper;
    @Autowired
    private ZcglHtglInfoService zcglHtglInfoService;
    @Autowired
    private ZcglHtglInfoChangeMapper zcglHtglInfoChangeMapper;
    @Autowired
    private ZcglHtglPabFytkMapper zcglHtglPabFytkMapper;
    @Autowired
    private ZcglHtglPabYjtkMapper zcglHtglPabYjtkMapper;
    @Autowired
    private ZcglHtglPabCwtkMapper zcglHtglPabCwtkMapper;
    @Autowired
    private ZcglHtglPabWytkMapper zcglHtglPabWytkMapper;
    @Autowired
    private ZcglHtglQtskzhMapper zcglHtglQtskzhMapper;
    @Autowired
    private ZcglHtglQtydtkMapper zcglHtglQtydtkMapper;


    @Override
    public List<Map<String, Object>> countByZcSource() {
        return null;
    }

    @Override
    public List<ZcglHtglInfoEntity> getList(ZcglHtglInfoPagination zcglHtglInfoPagination) {
        return getTypeList(zcglHtglInfoPagination, zcglHtglInfoPagination.getDataType());
    }

    @Override
    public List<ZcglHtglInfoEntity> getTypeList(ZcglHtglInfoPagination zcglHtglInfoPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int zcglHtglInfoNum = 0;
        QueryWrapper<ZcglHtglInfoEntity> zcglHtglInfoQueryWrapper = new QueryWrapper<>();
        int zcglHtglPabNum = 0;
        QueryWrapper<ZcglHtglPabEntity> zcglHtglPabQueryWrapper = new QueryWrapper<>();
        long zcglHtglPabcount = zcglHtglPabService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(zcglHtglInfoPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcglHtglInfoPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            int zcglHtglInfoNum1 = 0;
            QueryWrapper<ZcglHtglInfoEntity> zcglHtglInfoSuperWrapper = new QueryWrapper<>();
            zcglHtglInfoNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglHtglInfoSuperWrapper, superQueryList, matchLogic, "zcglHtglInfo")
                    , new ZcglHtglInfoEntity(), zcglHtglInfoNum1);
            if (zcglHtglInfoNum1 > 0) {
                List<String> zcglHtglInfoList = this.list(zcglHtglInfoSuperWrapper).stream().map(ZcglHtglInfoEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(zcglHtglInfoList);
                intersectionSuperList.add(zcglHtglInfoList);
            }
            int zcglHtglPabNum1 = 0;
            QueryWrapper<ZcglHtglPabEntity> zcglHtglPabSuperWrapper = new QueryWrapper<>();
            zcglHtglPabNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglHtglPabSuperWrapper, superQueryList, matchLogic, "zcglHtglPab")
                    , new ZcglHtglPabEntity(), zcglHtglPabNum1);
            if (zcglHtglPabNum1 > 0 && zcglHtglPabcount > 0) {
                List<String> zcglHtglPabList = zcglHtglPabService.list(zcglHtglPabSuperWrapper).stream().map(ZcglHtglPabEntity::getParentid).collect(Collectors.toList());
                allSuperList.addAll(zcglHtglPabList);
                intersectionSuperList.add(zcglHtglPabList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcglHtglInfoObj = authorizeService.getCondition(new AuthorizeConditionModel(zcglHtglInfoQueryWrapper, zcglHtglInfoPagination.getMenuId(), "zcgl_htgl_info"));
                if (ObjectUtil.isEmpty(zcglHtglInfoObj)) {
                    return new ArrayList<>();
                } else {
                    zcglHtglInfoQueryWrapper = (QueryWrapper<ZcglHtglInfoEntity>) zcglHtglInfoObj;
                    zcglHtglInfoNum++;
                }
                Object zcglHtglPabObj = authorizeService.getCondition(new AuthorizeConditionModel(zcglHtglPabQueryWrapper, zcglHtglInfoPagination.getMenuId(), "zcgl_htgl_pab"));
                if (ObjectUtil.isEmpty(zcglHtglPabObj)) {
                    return new ArrayList<>();
                } else {
                    zcglHtglPabQueryWrapper = (QueryWrapper<ZcglHtglPabEntity>) zcglHtglPabObj;
                    zcglHtglPabNum++;
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcglHtglInfoObj = authorizeService.getCondition(new AuthorizeConditionModel(zcglHtglInfoQueryWrapper, zcglHtglInfoPagination.getMenuId(), "zcglHtglInfo"));
                if (ObjectUtil.isEmpty(zcglHtglInfoObj)) {
                    return new ArrayList<>();
                } else {
                    zcglHtglInfoQueryWrapper = (QueryWrapper<ZcglHtglInfoEntity>) zcglHtglInfoObj;
                    zcglHtglInfoNum++;
                }
                Object zcglHtglPabObj = authorizeService.getCondition(new AuthorizeConditionModel(zcglHtglPabQueryWrapper, zcglHtglInfoPagination.getMenuId(), "zcglHtglPab"));
                if (ObjectUtil.isEmpty(zcglHtglPabObj)) {
                    return new ArrayList<>();
                } else {
                    zcglHtglPabQueryWrapper = (QueryWrapper<ZcglHtglPabEntity>) zcglHtglPabObj;
                    zcglHtglPabNum++;
                }
            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(zcglHtglInfoPagination.getJnpf_zcgl_htgl_pab_jnpf_pabCustomerName())) {
                zcglHtglPabNum++;
                zcglHtglPabQueryWrapper.lambda().eq(ZcglHtglPabEntity::getPabCustomerName, zcglHtglInfoPagination.getJnpf_zcgl_htgl_pab_jnpf_pabCustomerName());
            }

            if (ObjectUtil.isNotEmpty(zcglHtglInfoPagination.getProject())) {
                zcglHtglInfoNum++;
                zcglHtglInfoQueryWrapper.lambda().eq(ZcglHtglInfoEntity::getProject, zcglHtglInfoPagination.getProject());
            }

        }


        if (zcglHtglPabNum > 0) {
            List<String> zcglHtglPabIdList = zcglHtglPabService.list(zcglHtglPabQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getParentid())).map(t -> t.getParentid()).collect(Collectors.toList());
            long count = zcglHtglPabService.count();
            if (count > 0) {
                intersectionList.add(zcglHtglPabIdList);
            }
            AllIdList.addAll(zcglHtglPabIdList);
        }
        total += zcglHtglPabNum;


        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            zcglHtglInfoQueryWrapper.lambda().in(ZcglHtglInfoEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            zcglHtglInfoQueryWrapper.lambda().and(t -> t.in(ZcglHtglInfoEntity::getId, finalAllSuperIDlist));
        }

        //排序
        if (StringUtil.isEmpty(zcglHtglInfoPagination.getSidx())) {
            zcglHtglInfoQueryWrapper.lambda().orderByDesc(ZcglHtglInfoEntity::getId);
        } else {
            try {
                String sidx = zcglHtglInfoPagination.getSidx();
                ZcglHtglInfoEntity zcglHtglInfoEntity = new ZcglHtglInfoEntity();
                Field declaredField = zcglHtglInfoEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                zcglHtglInfoQueryWrapper = "asc".equals(zcglHtglInfoPagination.getSort().toLowerCase()) ? zcglHtglInfoQueryWrapper.orderByAsc(value) : zcglHtglInfoQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<ZcglHtglInfoEntity> page = new Page<>(zcglHtglInfoPagination.getCurrentPage(), zcglHtglInfoPagination.getPageSize());
                IPage<ZcglHtglInfoEntity> userIPage = this.page(page, zcglHtglInfoQueryWrapper);
                return zcglHtglInfoPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<ZcglHtglInfoEntity> list = new ArrayList();
                return zcglHtglInfoPagination.setData(list, list.size());
            }
        } else {
            return this.list(zcglHtglInfoQueryWrapper);
        }
    }


    @Override
    public ZcglHtglInfoEntity getInfo(String id) {
        QueryWrapper<ZcglHtglInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcglHtglInfoEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcglHtglInfoEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcglHtglInfoEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(ZcglHtglInfoEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法
    @Override
    public ZcglHtglPabEntity getZcglHtglPab(String id) {
        QueryWrapper<ZcglHtglPabEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcglHtglPabEntity::getParentid, id);
        return zcglHtglPabService.getOne(queryWrapper);
    }


    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcglHtglInfoForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        if (isUp) {
            id = form.getId();
        }
        if (ObjectUtil.isNotEmpty(form.getZcgl_htgl_pab())) {
        }
        if (total > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<ZcglHtglPabSpaceVO> getPabSpace(String zcIds) {
        List<String> ids = new ArrayList<>();
        if (zcIds.contains(",") == false) {
            ids = new ArrayList<>();
            ids.add(zcIds);

        } else {
            ids = Arrays.asList(zcIds.split(","));

        }

        List<ZcglHtglPabSpaceVO> list = baseMapper.getPabSpace(ids);
        return list;
    }

    @Override
    public ActionResult createSkjh(ZcglHtglInfoForm zcglHtglInfoForm) {
        /*
         * 收款计划逻辑
         *   1.根据合同起止日期与付款周期来计算
         *       1.1循环条数算出每条对应字段数据
         *
         * */
        List<ZcglHtjhSkjhVO> list = new ArrayList<>();
        List<ZcglHtglPabFytkEntity> zcgl_htgl_pab_fytks = zcglHtglInfoForm
                .getZcgl_htgl_pab_fytks();

        zcgl_htgl_pab_fytks.stream().forEach(fytks -> {
            //根据合同起止时间计算月数（向上取整）
            Date startTi = zcglHtglInfoForm.getStartTime();
            Date endTi = zcglHtglInfoForm.getEndTime();
            // 计算月份差
            Long months = DateUtil.betweenMonth(DateUtil.date(startTi), DateUtil.date(endTi), true); // true 表示向上取整
            if (ZcglHtglPabFytkEntity.RENT_METHOD_WQX.equals(fytks.getRentMethod())) {
                months = 240L;
            }
            int intValueMonth = months.intValue();
            //判断是否优惠，如果有优惠需要减去优惠月数 且开始时间向后延优惠月数
            if (fytks.getIsAvailable().equals(ZcglHtglPabFytkEntity.YHDZ_1)) {
                //向后延优惠的月数
                startTi =  DateUtil.offsetMonth(startTi, Integer.valueOf(fytks.getAvailableMonth()));
                intValueMonth = intValueMonth - Integer.valueOf(fytks.getAvailableMonth());
            }
            // 检查付款周期是否为零
            if ("0".equals(fytks.getPaymentCycle())) {
                throw new ArithmeticException("错误: 付款周期月不能为零，请检查 。");
            }
            Integer paymentCyclein = Integer.valueOf(fytks.getPaymentCycle());
            Integer paymentCycle = intValueMonth / paymentCyclein;

            //交费初始时间
            Date startTime = startTi;
            double hsje = 0D;
            double bhsje = 0D;
            double ysje = 0D;//应收金额
            for (int i = 0; i < paymentCycle; i++) {
                BigDecimal monthlyRent = fytks.getMonthlyRent();//月租金
                ZcglHtjhSkjhVO zcglHtjhSkjhVO = new ZcglHtjhSkjhVO();
                zcglHtjhSkjhVO.setRelatedSpace(fytks.getRelatedSpace());
                zcglHtjhSkjhVO.setExpenseItem(ExpenseTypeEnum.getDescByCode(fytks.getExpenseType()));

                /*
                 * 区间计算逻辑
                 *   1.根据开始日期、付款周期、收款日固定天数来计算
                 *   2.还需要根据这个区间来生成账单里面的应收条款
                 * */

                Date finalDate = DateUtil.offsetMonth(startTime, Integer.valueOf(fytks.getPaymentCycle()));
                //向前再推一天
                finalDate = DateUtil.offsetDay(finalDate, -1);
                zcglHtjhSkjhVO.setIntervall(DateUtil.format(startTime, "yyyy-MM-dd") + "至" + DateUtil.format(finalDate, "yyyy-MM-dd"));
                zcglHtjhSkjhVO.setPaymentDate(DateUtil.format(startTime, "yyyy-MM-dd"));

                //计算含税和不含税金额且判断是否需要进行递增逻辑计算
//                if (hsje == 0D && bhsje == 0D) {
                if (ysje == 0D) {
                    // 使用BigDecimal计算，保持两位小数
//                    hsje = new BigDecimal(fytks.getHsUnitPrice()).multiply(new BigDecimal(fytks.getPaymentCycle()))
//                            .setScale(2, RoundingMode.HALF_UP).doubleValue();
//                    bhsje = new BigDecimal(fytks.getBhsUnitPrice()).multiply(new BigDecimal(fytks.getPaymentCycle()))
//                            .setScale(2, RoundingMode.HALF_UP).doubleValue();
                    ysje = monthlyRent.multiply(new BigDecimal(fytks.getPaymentCycle()))
                            .setScale(2, RoundingMode.HALF_UP).doubleValue();
                }
                /**=========================递增逻辑开始=======================================*/
                List<ZcglHtglInfoForm.IncrementalData> incrementalDatas = zcglHtglInfoForm.getIncrementalDatas();
                if (IterUtil.isNotEmpty(incrementalDatas) && incrementalDatas.size()>0) {
                    // 按递增开始时间排序
                    incrementalDatas = incrementalDatas.stream()
                            .sorted(Comparator.comparing(data -> DateUtil.parse(data.getIncrementalStartDate())))
                            .collect(Collectors.toList());

                    // 获取合同开始时间


                    // 遍历每个递增规则，按顺序应用符合条件的递增
                    for (ZcglHtglInfoForm.IncrementalData incrementalData : incrementalDatas) {
                        Date incrementalStartDate = DateUtil.parse(incrementalData.getIncrementalStartDate());

                        // 如果当前时间大于等于递增开始时间，则应用该递增规则
                        if (DateUtil.compare(startTime, incrementalStartDate) >= 0) {
                            Integer dzNum = Integer.valueOf(incrementalData.getIncrementalNum());

//                            // 根据递增类型执行不同的计算逻辑
//                            if (ZcglHtglInfoForm.DZ_TYPE_0.equals(incrementalData.getIncrementalType())) {
//                                // 百分比递增：在当前租金基础上增加指定百分比
//                                monthlyRent = monthlyRent * (1 + dzNum / 100.0);
//                            } else {
//                                // 固定金额递增：直接增加固定金额
//                                monthlyRent = monthlyRent + dzNum;
//                            }
// 根据递增类型执行不同的计算逻辑
                            if (ZcglHtglInfoForm.DZ_TYPE_0.equals(incrementalData.getIncrementalType())) {
                                // 百分比递增：在当前租金基础上增加指定百分比
                                // 计算方式：monthlyRent * (1 + dzNum / 100.0)
                                BigDecimal percentage = new BigDecimal(dzNum).divide(new BigDecimal("100"));
                                BigDecimal multiplier = BigDecimal.ONE.add(percentage);
                                monthlyRent = monthlyRent.multiply(multiplier);
                            } else {
                                // 固定金额递增：直接增加固定金额
                                monthlyRent = monthlyRent.add(new BigDecimal(dzNum));
                            }
                            System.out.println("应用递增规则: " + incrementalData.getIncrementalStartDate()
                                    + ", 递增类型: " + incrementalData.getIncrementalType()
                                    + ", 递增数值: " + dzNum
                                    + ", 新租金: " + monthlyRent);
                        } else {
                            // 由于已经排序，一旦遇到时间大于当前时间的规则，后续规则都不会应用，直接跳出循环
                            break;
                        }
                    }

                    // 计算最终应收金额（在所有符合条件的递增应用后）
                    ysje = monthlyRent
                            .multiply(new BigDecimal(fytks.getPaymentCycle()))
                            .setScale(2, RoundingMode.HALF_UP)
                            .doubleValue();
                }
/**=========================递增逻辑结束=======================================*/

                zcglHtjhSkjhVO.setInclusiveAmount(String.valueOf(ysje));
                zcglHtjhSkjhVO.setExcludingAmount(String.valueOf(ysje));
                zcglHtjhSkjhVO.setMonthlyRent(String.valueOf(monthlyRent));
                zcglHtjhSkjhVO.setTaxRate(fytks.getTaxRate());
                zcglHtjhSkjhVO.setSkjhType("正常费用");
                //计算出区间金额之后将开始时间赋值为结束时间便于下一次区间计算
                startTime = finalDate;
                list.add(zcglHtjhSkjhVO);
            }

            if("1".equals(fytks.getExpenseType())&&fytks.getEarnestMoney()!=null&&IterUtil.isNotEmpty(list)){
                // 创建新对象而不是复用已有对象
                ZcglHtjhSkjhVO depositRecord = new ZcglHtjhSkjhVO();

                // 从第一个记录复制必要的属性
                ZcglHtjhSkjhVO firstRecord = list.get(0);
                BeanUtil.copyProperties(firstRecord,depositRecord);
                // 设置保证金相关属性
                depositRecord.setInclusiveAmount(String.valueOf(fytks.getEarnestMoney()));
                depositRecord.setExcludingAmount(String.valueOf(fytks.getEarnestMoney()));
                depositRecord.setSkjhType("保证金");
                depositRecord.setExpenseItem("保证金");

                // 添加新创建的保证金记录
                list.add(depositRecord);
            }

        });




        //封装前端需要展示的收款计划
        Map<String, List<ZcglHtjhSkjhVO>> groupedBySpace = list.stream()
                .collect(Collectors.groupingBy(
                        item -> item.getRelatedSpace() == null ? "" : item.getRelatedSpace()));
        // 使用 for-each 循环遍历 entrySet
        List<NewZcglHtjhSkjhVO.SkjhEntity> lskjh = new ArrayList<>();
        for (Map.Entry<String, List<ZcglHtjhSkjhVO>> entry : groupedBySpace.entrySet()) {
            NewZcglHtjhSkjhVO.SkjhEntity skjhEntity = new NewZcglHtjhSkjhVO.SkjhEntity();
            //根据关联空间id查询出关联空间名称
            List<ZcglHtglPabSpaceVO> pabSpace = zcglHtglInfoService.getPabSpace(entry.getKey());
            String result = pabSpace.stream()
                    .map(ZcglHtglPabSpaceVO::getZcName)
                    .collect(Collectors.joining(","));
            skjhEntity.setRelatedSpace(result);
            //子表也要替换为中文
            entry.getValue().forEach(o -> {
                o.setRelatedSpace(result);
            });

            skjhEntity.setListSk(entry.getValue());

            lskjh.add(skjhEntity);
        }
        NewZcglHtjhSkjhVO newZcglHtjhSkjhVO = new NewZcglHtjhSkjhVO();
        newZcglHtjhSkjhVO.setZcglHtglInfoForm(zcglHtglInfoForm);
        newZcglHtjhSkjhVO.setSkjhEntitys(lskjh);
        return ActionResult.success(newZcglHtjhSkjhVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void htglInfoChange(ZcglHtglInfoChangeEntity htglEntity) {

        ZcglHtglInfoChangeEntity entity = zcglHtglInfoChangeMapper.selectById(htglEntity.getId());

        //变更json
        String newData = entity.getNewData();
        //合同id
        String htdgId = entity.getHtdgId();
        ZcglHtglInfoForm zcglHtglInfoForm = JSONUtil.toBean(newData, ZcglHtglInfoForm.class);
        if (ZcglHtglInfoChangeEntity.TYPE_1.equals(entity.getType())) {
            ZcglHtglInfoEntity zcglHtglInfoEntity = new ZcglHtglInfoEntity();
            BeanUtil.copyProperties(zcglHtglInfoForm, zcglHtglInfoEntity);
            baseMapper.updateById(zcglHtglInfoEntity);
            List<ZcglHtglPabModel> pabList = zcglHtglInfoForm.getZcgl_htgl_pab();
            if (IterUtil.isNotEmpty(pabList)) {
                zcglHtglPabMapper.delete(new QueryWrapper<ZcglHtglPabEntity>()
                        .eq("F_PARENTID", htdgId)
                );
                pabList.stream().forEach(i -> {
                    ZcglHtglPabEntity zcglHtglPabEntity = new ZcglHtglPabEntity();
                    BeanUtil.copyProperties(i, zcglHtglPabEntity);
                    zcglHtglPabEntity.setParentid(htdgId);
                    zcglHtglPabMapper.insert(zcglHtglPabEntity);
                });
            }


        }

        if (ZcglHtglInfoChangeEntity.TYPE_2.equals(entity.getType())) {
            ZcglHtglInfoEntity zcglHtglInfoEntity = new ZcglHtglInfoEntity();
            BeanUtil.copyProperties(zcglHtglInfoForm, zcglHtglInfoEntity);
            baseMapper.updateById(zcglHtglInfoEntity);
            JSONObject jsonObject = JSONObject.parseObject(newData);
            //费用条款
            List<ZcglHtglPabFytkEntity> zcglHtglPabFytkEntityNew = JSONUtil.toList(jsonObject.get("zcgl_htgl_pab_fytk").toString(), ZcglHtglPabFytkEntity.class);
            if (IterUtil.isNotEmpty(zcglHtglPabFytkEntityNew)) {
                zcglHtglPabFytkMapper.delete(new QueryWrapper<ZcglHtglPabFytkEntity>()
                        .eq("F_PARENTID", htdgId)
                );
                zcglHtglPabFytkEntityNew.stream().forEach(i -> {
                    ZcglHtglPabFytkEntity zcglHtglPabFytkEntity = new ZcglHtglPabFytkEntity();
                    BeanUtil.copyProperties(i, zcglHtglPabFytkEntity);
                    zcglHtglPabFytkMapper.insert(zcglHtglPabFytkEntity);
                });
            }

            //押金条款
            ZcglHtglPabYjtkEntity zcglHtglPabYjtkEntityNew = JSONUtil.toBean(jsonObject.get("zcgl_htgl_pab_yjtk").toString(), ZcglHtglPabYjtkEntity.class);
            if (ObjectUtil.isNotEmpty(zcglHtglPabYjtkEntityNew)) {
                zcglHtglPabYjtkMapper.update(zcglHtglPabYjtkEntityNew, new QueryWrapper<ZcglHtglPabYjtkEntity>()
                        .eq("F_PARENTID", htdgId)
                );
            }
            //车位条款
            ZcglHtglPabCwtkEntity zcglHtglPabCwtkEntityNew = JSONUtil.toBean(jsonObject.get("zcgl_htgl_pab_cwtk").toString(), ZcglHtglPabCwtkEntity.class);
            if (ObjectUtil.isNotEmpty(zcglHtglPabCwtkEntityNew)) {
                zcglHtglPabCwtkMapper.update(zcglHtglPabCwtkEntityNew, new QueryWrapper<ZcglHtglPabCwtkEntity>()
                        .eq("F_PARENTID", htdgId)
                );
            }
            //违约条款
            ZcglHtglPabWytkEntity zcglHtglPabWytkEntityNew = JSONUtil.toBean(jsonObject.get("zcgl_htgl_pab_wytk").toString(), ZcglHtglPabWytkEntity.class);
            if (ObjectUtil.isNotEmpty(zcglHtglPabWytkEntityNew)) {
                zcglHtglPabWytkMapper.update(zcglHtglPabWytkEntityNew, new QueryWrapper<ZcglHtglPabWytkEntity>()
                        .eq("F_PARENTID", htdgId)
                );
            }
        }

        if (ZcglHtglInfoChangeEntity.TYPE_3.equals(entity.getType())) {
            ZcglHtglInfoEntity zcglHtglInfoEntity = new ZcglHtglInfoEntity();
            BeanUtil.copyProperties(zcglHtglInfoForm, zcglHtglInfoEntity);
            baseMapper.updateById(zcglHtglInfoEntity);
            JSONObject jsonObject = JSONObject.parseObject(newData);
            //其他收款账户
            List<ZcglHtglQtskzhEntity> zcglHtglQtskzhEntityNew = JSONUtil.toList(jsonObject.get("zcgl_htgl_qtskzh").toString(), ZcglHtglQtskzhEntity.class);
            if (IterUtil.isNotEmpty(zcglHtglQtskzhEntityNew)) {
                zcglHtglQtskzhMapper.delete(new QueryWrapper<ZcglHtglQtskzhEntity>()
                        .eq("F_PARENTID", htdgId)
                );
                zcglHtglQtskzhEntityNew.stream().forEach(i -> {
                    ZcglHtglQtskzhEntity zcglHtglQtskzhEntity = new ZcglHtglQtskzhEntity();
                    BeanUtil.copyProperties(i, zcglHtglQtskzhEntity);
                    zcglHtglQtskzhMapper.insert(zcglHtglQtskzhEntity);
                });
            }

            //其他约定条款
            List<ZcglHtglQtydtkEntity> zcglHtglQtydtkEntityNew = JSONUtil.toList(jsonObject.get("zcgl_htgl_qtydtk").toString(), ZcglHtglQtydtkEntity.class);
            if (IterUtil.isNotEmpty(zcglHtglQtydtkEntityNew)) {
                zcglHtglQtydtkMapper.delete(new QueryWrapper<ZcglHtglQtydtkEntity>()
                        .eq("F_PARENTID", htdgId)
                );
                zcglHtglQtydtkEntityNew.stream().forEach(i -> {
                    ZcglHtglQtydtkEntity zcglHtglQtydtkEntity = new ZcglHtglQtydtkEntity();
                    BeanUtil.copyProperties(i, zcglHtglQtydtkEntity);
                    zcglHtglQtydtkMapper.insert(zcglHtglQtydtkEntity);
                });
            }

        }

        if (ZcglHtglInfoChangeEntity.TYPE_4.equals(entity.getType())) {
            ZcglHtglInfoEntity zcglHtglInfoEntity = new ZcglHtglInfoEntity();
            BeanUtil.copyProperties(zcglHtglInfoForm, zcglHtglInfoEntity);
            zcglHtglInfoEntity.setHtStart(ZcglHtglInfoEntity.START_1);
        }

    }

    @Override
    public BigDecimal getYingShouByHtNoNowYear(String htNo) {
        return baseMapper.getYingShouByHtNoNowYear(htNo);
    }

    @Override
    public BigDecimal getYingShouByHtNoThisMonth(String htNo) {
        return baseMapper.getYingShouByHtNoThisMonth(htNo);
    }

}
